import { connect } from 'react-redux'
import { createIncrementAction, createDecrementAction, createAsyncIncrementAction } from '../../redux/actions/count'
import React, { Component } from 'react';

class Count extends Component {

    // 有了actionCreator ， 我们就不需要自己再去定义action了
    increment = () => {
        const { value } = this.countNum;
        this.props.increment(value * 1)
    }

    decrement = () => {
        const { value } = this.countNum;
        this.props.decrement(value * 1)
    }

    incrementIfOdd = () => {
        const { value } = this.countNum;
        if (this.props.count % 2 === 1) {
            this.props.increment(value * 1)
        }
    }


    incrementAsync = () => {
        const { value } = this.countNum;
        this.props.incrementAsync(value * 1, 500)
    }

    render() {
        return (
            <div>
                <h2>总数为： {this.props.count}</h2>
                <select ref={a => this.countNum = a}>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                </select>&nbsp;
                <button onClick={this.increment}>+</button>&nbsp;
                <button onClick={this.decrement}>-</button>&nbsp;
                <button onClick={this.incrementIfOdd}>add if odd</button>&nbsp;
                <button onClick={this.incrementAsync}>add async</button>&nbsp;
            </div>
        )
    }
}


/**
 * 由于 UI组件并不能直接获取redux管理的状态，所以这里的话需要由
 * 容器组价将状态以及操作状态的方法作为参数传递到connect()函数中
 */

// 该方法返回的UI组件所需要获取的redux管理的状态属性
// function mapStateToProps(state) {
//     return { count: state }
// }

// 该方法返回的UI组件所需要的操作对应状态的方法
// function mapDispatchToProps(dispatch) {
//     return {
//         increment: createIncrementAction,
//         decrement: createDecrementAction,
//         incrementAsync: createAsyncIncrementAction
//     }
// }

// 作为参数传入后，UI组件可以通过props属性读取对应的值
export default connect(
    state => ({count: state.count }),
    {
        increment: createIncrementAction,
        decrement: createDecrementAction,
        incrementAsync: createAsyncIncrementAction
    }
)(Count);